package common;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Connection {
    private Socket             socket = null;
    private ObjectOutputStream out;
    private ObjectInputStream  in;

    public Connection(Socket s) {
        try {
            this.socket = s;
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void send(Object o) {
        try {
            out.writeObject(o);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected Object receive() {
        Object result = null;
        try {
            result = in.readObject();
            in.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String getHost() {
        return this.socket.getLocalAddress().getHostAddress();
    }

    public int getPort() {
        return this.socket.getLocalPort();
    }
}
